<template>
  <div class="update">
    <Doctor :doctor="doctor" @update="update" @remove="remove" :disabled="disabled"/>
  </div>
</template>

<script>
// @ is an alias to /src
import Doctor from '@/components/Doctor';
import { validate } from '@/util/index';

export default {
  name: 'updateDoctor',

  components: {
    Doctor
  },

  data() {
    return {
      doctor: {},
      disabled: false
    }
  },

  methods: {
    update(doctor) {
      const fields = ['dc_name', 'dc_pic', 'working_week', 'start_hour', 'end_hour', 'dc_intro', 'dc_skill'];
      const isValidated = validate(this.$weui.form, this.doctor, fields);

      if (this.disabled || !isValidated) {
        return false;
      }
      this.disabled = true;
      this.$axios
        .put(`http://api.qy-clinic.com/doctor/${doctor.dc_id}`, doctor)
        .then(() => {
          this.disabled = false;
          this.$weui.toast('更新成功', 1500);
        })
        .catch(() => {
          this.disabled = false;
          this.$weui.alert('更新失败');
        });
    },
    remove(id) {
      this.$weui.confirm('确认要删除这个医生吗', () => {
        const loading = this.$weui.loading('删除中...')
        this.$axios
          .put(`http://api.qy-clinic.com/doctor/${id}`, { dc_status: false })
          .then(({ data }) => {
            if (data[0] <= 0) {
              throw new Error(data.name);
            }
            loading.hide();
            this.$weui.toast('删除成功', 1500);
            this.$router.push({ name: 'home' });
          })
          .catch(() => {
            loading.hide();
            this.$weui.alert('删除失败');
          })
      },
      { title: '警告' });
    },
  },

  mounted() {
    const { doctorId } = this.$route.params;

    this.$axios
      .get(`http://api.qy-clinic.com/doctors/${doctorId}`)
      .then(({ data: [doctor] }) => {
        this.doctor = doctor;
      });
  }
}
</script>
